/* 
 * File:   TUServer.cpp
 * Author: arschmitz
 *
 * Created on April 3, 2011, 12:47 PM
 */

#include <cstdlib>
#include <cstdio>
#include <iostream>
#include "TigerUpdate.h"
#define CONFIG_FILENAME "config.conf"

using namespace std;

TUServer::TUServer(){
    char allAddr[] = "255.255.255.255";
    myAddress = new TUAddress(allAddr, 53197);
    mySocket = new TUSocket(myAddress);
    mySocket->bindMe();
}
TUServer::TUServer(int port){
    char allAddr[] = "255.255.255.255";
    myAddress = new TUAddress(allAddr, port);
    mySocket = new TUSocket(myAddress);
    mySocket->bindMe();
}
TUServer::TUServer(TUAddress acceptedAddress) {
    this->myAddress = &acceptedAddress;
    this->mySocket = new TUSocket(myAddress);
    mySocket->bindMe();
}
TUServer::~TUServer() {
    delete myAddress;
    delete mySocket;
    delete this;
}

int TUServer::waitForClient() {
    TUAddress *client;
    TUObject *object;
    TUObject *sObj = NULL;
    bool send = false;
    while(true){
        mySocket->recvMe(object, client);
        if(object->isAMessage() && !fork()){
            //Child Process
            TUMessage *msg = (TUMessage *) object;
            switch(msg->getType()){
                case(0x00): switch(msg->getCode()){
                            case(0x00): sObj = new TUMessage(0x10, 0x00, NULL); send=true; break;
                            case(0x10): sObj = new TUFile(CONFIG_FILENAME, fopen(CONFIG_FILENAME, "r")); send=true; break;
                            case(0x11): break; //Send config Hash MD5
                            case(0x12): break; //Send config Hash SHA-2
                            } //End code switch
                default: exit(0); //Close the thread & ignore
            } //End type switch
            if(send){
                serveObject(sObj, client);
            }
        } // End fork
    }
}
int TUServer::serveObject(TUObject *object, TUAddress *client) {
    return ((new TUSocket(client))->sendMe(object));
}